<?php

namespace Remoteshell\PhpBotSdk\request_lib;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Promise;
use Remoteshell\PhpBotSdk\announce\HttpsInterface;
use Remoteshell\PhpBotSdk\announce\QQBotURL;
use Remoteshell\PhpBotSdk\logger\LoggerRecoder;
use Symfony\Component\HttpFoundation\Request;

class MainHttps implements QQBotURL, HttpsInterface
{
    private static $url;

    private static $appid;

    private static $appkey;

    private static $token;

    private static $expires_in;

    private static Client $client;

    private static LoggerRecoder $logger;

    /**
     * SendHttpsRequest constructor.
     * 初始化
     */
    public function __construct()
    {
        self::$url = self::URL;
    }

    /**
     * @return string
     * 返回一个URL字符串
     */
    public function getUrl(): string
    {
        return self::$url;
    }

    /**
     * 返回ACCESS TOKEN以及到期时间
     * @return array
     */
    public function getAccessToken(): array
    {
        return ["token" => self::$token, "timeout" => self::$expires_in];
    }

    /**
     * @return mixed
     */
    public function getHeaders(): array
    {
        $token = $this->getAccessToken();
        return [
            'Authorization' => "QQBot " . $token['token'],
        ];
    }

    /**
     * 使用GUZZLE发送一个普通的HTTPS请求(用于验证！！)
     * @param array $params 包含appid和appkey的关联数组
     * @return mixed
     */
    public function SendNormalHttps(array $params): mixed
    {
        self::$client = new Client();
        self::$logger = new LoggerRecoder();
        // 检查参数是否包含appid和appkey
        if (!isset($params['appid']) || !isset($params['appkey'])) {
            echo "你没有传递appID或appKey！";
            return false;
        }

        self::$appid = $params['appid'];
        self::$appkey = $params['appkey'];

        try {
            // 发送POST请求，并传递JSON数据
            $response = self::$client->request('POST', self::$url, [
                'json' => [
                    'appId' => self::$appid,
                    'clientSecret' => self::$appkey,
                ],
                'headers' => [
                    'Content-Type' => 'application/json',
                ],
                'verify' => false
            ]);
            $decode_result = json_decode($response->getBody(), true);
            if (isset($decode_result['code']) && $decode_result['code'] == 100016) {
                $body = $response->getBody();
            //    self::$logger ->record("error", "appid或appkey错误！Response Json:$body");
                echo "appid或appkey错误！";
                return false;
            } else {
                $body = $response->getBody();
              //  self::$logger ->record("normal", "鉴权成功！Response Json:$body");
            //    echo "appid或appkey正确！";
            }

            if (isset($decode_result['access_token']) && isset($decode_result['expires_in'])){
                self::$token = $decode_result['access_token'];
                self::$expires_in = $decode_result['expires_in'];
            }
            return $response;
        } catch (RequestException $e) {
            // 处理请求异常
            echo '请求失败: ' . $e->getMessage();
            self::$logger ->record("critical", "请求失败！". $e->getMessage());

            return false;
        }
    }

    /**
     * 异步HTTPS请求（用于验证！！！）
     * @param array $params 包含appid和appkey的关联数组
     * @return mixed
     */
    public function SendAsyncHttps(array $params): mixed
    {
        $client = new Client();
        $logger = new LoggerRecoder();
        // 检查参数是否包含appid和appkey
        if (!isset($params['appid']) || !isset($params['appkey'])) {
            echo "你没有传递appID或appKey！";
            return false;
        }

        self::$appid = $params['appid'];
        self::$appkey = $params['appkey'];

        try {
            // 发送异步POST请求，并传递JSON数据
            $promise = $client->requestAsync('POST', self::$url, [
                'json' => [
                    'appId' => self::$appid,
                    'clientSecret' => self::$appkey,
                ],
                'headers' => [
                    'Content-Type' => 'application/json',
                ],
                'verify' => false
            ]);

            // 等待请求完成
            $response = $promise->wait();

            $decode_result = json_decode($response->getBody(), true);
            if (isset($decode_result['code']) && $decode_result['code'] == 100016) {
                $body = $response->getBody();
                $logger->record("error", "appid或appkey错误！Response Json:$body");
                echo "appid或appkey错误！";
                return false;
            } else {
                $body = $response->getBody();
        //        $logger->record("normal", "鉴权成功！Response Json:$body");
            //    echo "appid或appkey正确！";
            }

            if (isset($decode_result['access_token']) && isset($decode_result['expires_in'])){
                self::$token = $decode_result['access_token'];
                self::$expires_in = $decode_result['expires_in'];
            }
            return $response;
        } catch (RequestException $e) {
            // 处理请求异常
            echo '请求失败: ' . $e->getMessage();
            $logger->record("critical", "请求失败！". $e->getMessage());

            return false;
        }
    }

    /**
     * 返回一个HTTPS客户端
     * @return Client
     */
    public static function getClient(): Client
    {
        return new Client();
    }

    /**
     * 返回一个请求工具
     * @return Request
     */
    public static function getRequest(): Request
    {
        return Request::createFromGlobals();
    }
}

